
/*
*用户相关操作
* */

import Cookie from 'js-cookie'
import {userTokenName} from "../config";

const Base64 = require('js-base64').Base64

//设置全局登录用户
const setLocalUser=(user)=>{
  let str=JSON.stringify(user)
  //cookie不能直接存中文字符串 用Base64编码
  let encode=Base64.encode(str);
  Cookie.set(userTokenName,encode)
}
//获取全局登录用户
const getLocalUser=()=>{
  let str=Cookie.get(userTokenName) ? Cookie.get(userTokenName) : '';
  return decode(str);
}
//服务端请求获取登录用户
const getLocalUserInServer=(req)=>{
  let service_cookie = {};
  req && req.headers.cookie && req.headers.cookie.split(';').forEach(function (val) {
    let parts = val.split('=');
    service_cookie[parts[0].trim()] = (parts[1] || '').trim();
  });
  let str= service_cookie[userTokenName]?service_cookie[userTokenName] : ''
  return decode(str);
}
//删除全局登录用户
const removeLocalUser=()=>{
  Cookie.remove(userTokenName)
}
let decode=(str)=>{
  try {
    let decode=str?Base64.decode(str):null;
    return decode?JSON.parse(decode):null;
  }catch (e) {
    return null;
  }
}
export{
  setLocalUser,getLocalUser,getLocalUserInServer,removeLocalUser
}
